using UnityEngine;
using System.Collections;

[ExecuteInEditMode()]
[AddComponentMenu("GK/Engine/GameCore/2D/Transform/gkScreenDraggingController")]
[RequireComponent(typeof(gkScreenTransform))]
/// \class  gkGUIRenderer
/// \brief 	The base component for GUI renderering
public class gkScreenDraggingController : MonoBehaviour, gkITickable
{		
	/// Is the object dragged
	private bool m_bDragged;
	
	/// The screen transform
	private gkScreenTransform m_rScreenTransform;
	
	/// The last pointer position
	private Vector2 m_f2PointerPosition;
	
	/// \brief  Called before first update
	void Start()
	{
		// Grab the screen transform
		m_rScreenTransform = GetComponent<gkScreenTransform>();
	}
	
	/// \brief  Called each frame
	public void Tick()
	{
		if(m_bDragged == false)
		{
			if(CanBeginToDrag())
			{
				StartDragging();
			}
		}
		else
		{
			if(CanContinueToDrag())
			{
				UpdateDragging();
			}
			else
			{
				EndDragging();
			}
		}
	}
	
	/// \brief  Can we begin to drag
	bool CanBeginToDrag()
	{
		if(GetPointerDown())
		{
			if(IsTouched(GetPointerPosition()))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else
		{
			return false;
		}
	}
	
	/// \brief  Can we begin to drag
	bool CanContinueToDrag()
	{
		return GetPointerUp() == false;
	}
	
	/// \brief  Start the dragging
	void StartDragging()
	{
		m_bDragged = true;
	}
	
	/// \brief  End the dragging
	void EndDragging()
	{
		m_bDragged = false;
		m_rScreenTransform.positionInPixel = GetPointerPosition();
	}
	
	/// \brief  Update the dragging
	void UpdateDragging()
	{
		m_rScreenTransform.positionInPixel = GetPointerPosition();
	}
	
	/// \brief  Is the draggable object touched?
	bool IsTouched(Vector2 a_f2ScreenPositionInPixel)
	{
		return m_rScreenTransform.ContainsScreenPoint(a_f2ScreenPositionInPixel);
	}
	
	/// \brief  Get Is the pointer down this update
	bool GetPointerDown()
	{
		if(Application.isEditor)
		{
			Event currentEvent;
			
			// Get the current GUI event
			currentEvent = Event.current;
			
			if(currentEvent != null)
			{
				return (currentEvent.type == EventType.mouseDown);
			}
			else
			{
				return false;
			}
		}
		else
		{
			return Input.GetMouseButtonDown(0);
		}
	}
	
	/// \brief  Get Is the pointer up this update
	bool GetPointerUp()
	{
		if(Application.isEditor)
		{
			Event currentEvent;
			
			// Get the current GUI event
			currentEvent = Event.current;
			
			if(currentEvent != null)
			{
				return (currentEvent.type == EventType.mouseUp);
			}
			else
			{
				return false;
			}
		}
		else
		{
			return Input.GetMouseButtonUp(0);
		}
	}
	
	/// \brief  Get Pointer Position
	Vector2 GetPointerPosition()
	{
		if(Application.isEditor)
		{
			Event currentEvent;
			
			// Get the current GUI event
			currentEvent = Event.current;
			
			if(currentEvent != null)
			{
				m_f2PointerPosition = currentEvent.mousePosition;
			}
		}
		else
		{
			m_f2PointerPosition = Input.mousePosition;
		}
		
		return m_f2PointerPosition;
	}
}